﻿<template>
    <el-container>
        <el-header>
            <div class="left-panel">
                <el-button type="primary"   icon="el-icon-plus" v-show="orgType==2" :disabled="!addState" @click="opAdd" >新增</el-button>
            </div>
            <div class="right-panel">
                <el-button :icon="Search"   type="primary" @click="opBindData">查询</el-button>
                <el-button :icon="Search" type="info" plain @click="resetSearch">重置</el-button>
                <el-button text type="primary" @click="showCondition = !showCondition">
                    <span v-if="!showCondition">展开</span>
                    <span v-else>收起</span>
                    <vab-icon
                        class="vab-dropdown"
                        :class="{ 'vab-dropdown-active': fold }"
                        icon="arrow-up-s-line"
                    />
                </el-button>
            </div>
        </el-header>
        <el-foot v-show="showCondition">
            <vab-query-form-top-panel>
                <el-form inline label-width="49px" :model="queryForm" style="margin-top: 5px">
                    <el-form-item label="申请编号" label-width="100px">
                        <el-input
                            placeholder="---请输入申请编号---"
                            v-model="queryList.afterOrderCode"
                            style="width: 250px"
                        />
                    </el-form-item>
                    <el-form-item label="申请单位" label-width="100px">
                        <el-input
                            placeholder="---请输入申请单位---"
                            v-model="queryList.storeName"
                            style="width: 250px"
                        />
                    </el-form-item>
                    <el-form-item label="申请类型" label-width="100px">
                        <el-select
                            placeholder="---请选择申请类型---"
                            v-model="queryList.afterOrderType"
                            style="width: 250px"
                        >
                            <el-option label="---请选择---" value />
                            <el-option
                                v-for="item in optionsAfterOrderType"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="退货时间" label-width="100px">
                        <el-date-picker
                            style="width: 250px"
                            v-model="queryList.dates"
                            type="datetimerange"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            format="YYYY-MM-DD HH:mm:ss"
                            range-separator="-"
                            unlink-panels="true"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            :default-time="defaultTime"
                        />
                    </el-form-item>
                    <el-form-item label="申请人" label-width="100px">
                        <el-input
                            placeholder="---请输入申请人---"
                            v-model="queryList.createName"
                            style="width: 250px"
                        />
                    </el-form-item>
                    <el-form-item label="关联单号" label-width="100px">
                        <el-input
                            placeholder="---请输入关联单号---"
                            v-model="queryList.applyOrderCode"
                            style="width: 250px"
                        />
                    </el-form-item>

                    <el-form-item label="状态" label-width="100px">
                        <el-select
                            placeholder="---请选择状态---"
                            v-model="queryList.status"
                            style="width: 250px"
                        >
                            <el-option label="---请选择---" value />
                            <el-option
                                v-for="item in optionsStatus"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="供应商" label-width="100px">
                        <el-input
                            placeholder="---请输入供应商---"
                            v-model="queryList.supplierName"
                            style="width: 250px"
                        />
                    </el-form-item>



                    <el-form-item label="物料简码" label-width="100px">
                        <el-input
                            placeholder="---请输入物料简码---"
                            v-model="queryList.materialSimpCode"
                            style="width: 250px"
                        />
                    </el-form-item>
                    <el-form-item label="物料编码" label-width="100px">
                        <el-input
                            placeholder="---请输入物料编码---"
                            v-model="queryList.materialCode"
                            style="width: 250px"
                        />
                    </el-form-item>
                    <el-form-item label="物料分类" label-width="100px">

                        <el-tree-select
                        placeholder="---请选择物料分类---"
                            v-model="queryList.materialTypeIds"
                            :props="{ label: 'label', value:'value',children: 'children' }"
                            :data="materialTypeTree"
                            multiple
                            :render-after-expand="false"
                            show-checkbox
                            style="width: 250px"
                        />
                    </el-form-item>
                    <el-form-item label="物料名称" label-width="100px">
                        <el-input
                            placeholder="---请输入物料名称---"
                            v-model="queryList.materialName"
                            style="width: 250px"
                        />
                    </el-form-item>

                </el-form>
            </vab-query-form-top-panel>
        </el-foot>
        <el-main class="nopadding">
            <scTable
                ref="mytable"
                :queryType="'after-order/item-pages'"
                :data="listData"
                :queryList="queryList"
                :column="columnList"
                :orderList="OrderList"
                :sort-orders="['ascending', 'descending']"
                @selection-change="selectionChange"
                row-key="StoreId"
                key="StoreId"
                border
                show-summary
                remoteSummary
                :span-method="objectSpanMethod"
                @row-click="rowClick"
                :row-style="selectedStyle"
            >
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column label="序号" type="index" width="60" />
                <el-table-column prop="afterOrderTime" label="退货时间" width="170" sortable></el-table-column>
                <el-table-column prop="afterOrderCode" label="申请编号" width="150" sortable></el-table-column>
                <el-table-column prop="storeName" label="申请单位" width="150" sortable></el-table-column>
                <el-table-column prop="afterOrderTypeDesc" label="申请类型" width="120" sortable></el-table-column>
                <el-table-column prop="materialCode" label="物料编码" width="120" sortable></el-table-column>
               
                <el-table-column prop="materialName" label="物料名称" width="250" sortable>
                    <template #default="scope">
                        <div v-if="scope.row.applyOrderId>0 && scope.row.price<=0">
                            {{scope.row.materialName}}   <el-tag type="danger" effect="light">赠</el-tag>
                        </div>
                        <div v-else>
                            <div style="color: #318cf2; cursor: pointer;" @click="handlePreview(scope.row)">
                                            {{scope.row.materialName}}
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="newUnitName" label="单位" width="100" sortable></el-table-column>
                <el-table-column prop="qty" label="申请数量" width="100" ></el-table-column>
                <el-table-column prop="receiveQty" label="实际接单数量" width="150">
                    <template #default="scope">
                        {{scope.row.receiveQty}}

                    </template>
                </el-table-column>
                <el-table-column prop="price" label="单价" width="100" sortable></el-table-column>
                <el-table-column prop="totalAmount" label="总额" width="100" sortable>
                    <template #default="scope">
                        <span>{{(scope.row.price * (scope.row.receiveQty?scope.row.receiveQty:scope.row.qty)).toFixed(2)}}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="supplierName" label="供货单位" width="150" sortable show-overflow-tooltip></el-table-column>
                <!-- <el-table-column prop="applyOrderCode" label="关联单号" width="200" sortable>
                    <template #default="scope"> <span class="goto" @click="goTo(scope.row, scope.$index)">{{scope.row.applyOrderCode}}</span></template>
                </el-table-column> -->
                <el-table-column prop="createName" label="申请人" width="120" sortable></el-table-column>

                <el-table-column prop="remarks" label="备注" width="150" sortable></el-table-column>
                <el-table-column prop="statusDesc" label="状态" width="120" sortable>
                    <template #default="scope">

                        <span style="color:#E6A23C;align-items: center;display: flex;"   v-if="scope.row.status==0"><el-icon><WarnTriangleFilled /></el-icon> {{scope.row.statusDesc}}</span>
                        <span style="color:#67C23A;align-items: center;display: flex;"   v-else-if="scope.row.status==1"><el-icon><CircleCheck /></el-icon> {{scope.row.statusDesc}}</span>
                        <span style="color:#F56C6C;align-items: center;display: flex;"   v-else-if="scope.row.status==2"><el-icon><CircleClose /></el-icon> {{scope.row.statusDesc}}</span>
                        <span style="color:#F56C6C;align-items: center;display: flex;"   v-else-if="scope.row.status==3"><el-icon><Back /></el-icon> {{scope.row.statusDesc}}</span>
                        <span style="color:#909399;align-items: center;display: flex;"   v-else-if="scope.row.status==4"><el-icon><Lock /></el-icon> {{scope.row.statusDesc}}</span>
                        <span style="color:#F56C6C;align-items: center;display: flex;"   v-else-if="scope.row.status==5"><el-icon><RefreshLeft /></el-icon> {{scope.row.statusDesc}}</span>
                        <span style="color:#909399;align-items: center;display: flex;"   v-else-if="scope.row.status==6"><el-icon><Finished /></el-icon> {{scope.row.statusDesc}}</span>
                        <span v-else>{{ scope.row.statusDesc }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" align="right" width="200">
                    <template #default="scope">
                        <el-button-group>
                            <el-button text  type="primary" size="small" @click="opShow(scope.row, scope.$index)">查看</el-button>
                            <el-button text type="primary" size="small"  @click="opEdit(scope.row, scope.$index)" v-if="scope.row.status==2 || scope.row.status==3 || scope.row.status==4 ||scope.row.status==5">编辑</el-button>
                            <el-popconfirm title="确定撤回吗？"  @confirm="opState(scope.row, 5)" v-if="scope.row.status==0">
                                <template #reference>
                                    <el-button  text type="danger"  size="small">撤回</el-button>
                                </template>
                            </el-popconfirm>
                            <el-popconfirm title="确定终止吗？"  @confirm="opState(scope.row,6)" v-if="scope.row.status==2 || scope.row.status==3 || scope.row.status==4 || scope.row.status==5">
                                <template #reference>
                                    <el-button  text type="danger"  size="small">终止</el-button>
                                </template>
                            </el-popconfirm>
                        </el-button-group>
                    </template>
                </el-table-column>
            </scTable>
        </el-main>
    </el-container>

    <save-dialog
        v-if="dialogSave"
        ref="saveDialog"
        @fatherMethod="opBindData"
        @success="handleSaveSuccess"
        @closed="dialogSave = false"
    ></save-dialog>
      <!-- 预览组件 -->
      <el-image-viewer v-if="showImage" @close="closeViewer" :url-list="srcList" />
</template>

<script>
import saveDialog from "./save";
import publicjs from "@/api/model/publicjs";
import tool from "@/utils/tool";
import config from "@/config";
export default {
    name: "afterListStore",
    components: {
        saveDialog,
        publicjs,
    },
    data() {
        return {
            dialogSave: false,
            dialogDetail: false,
            //审核状态
            auditState:false,
            showCondition: false,
            selectionRows: [],
            pkList: ["StoreId"],
            columnList: [],
            OrderList: { StoreId: "Asc" },
            queryList: {
            },
            result: "", // 运行结果
            props1: {
                checkStrictly: true,
                emitPath: false,
            },
            orgCodeList: "",
            orgNameList: "",
            addState: true, //可以增加
            editState: true, //可以修改
            editBatchState: true, //可以批量修改
            deleteState: true, //可以删除
			optionsStatus:[],//状态
            optionsAfterOrderType:[],//申请类型
            materialTypeTree:[],
            orgType:1,

            afterOrderId:"",//售后ID
            auditStateValue:"",//审核状态值
            auditRemarks:"",//审核备注

            activeRowIndex: null, // 存储被点击行的索引
             //预览图片
             previewUrl: [],
            //预览图片列表
            srcList: [],
            showImage: false,
            defaultTime:[
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 2, 1, 23, 59, 59),
            ]
        };
    },
    methods: {
        //添加
        opAdd() {
            this.dialogSave = true;
            this.$nextTick(() => {
                this.$refs.saveDialog.open("Add");
            });
        },
        //编辑
        opEdit(row) {
            this.dialogSave = true;
            this.$nextTick(() => {
                this.$refs.saveDialog.open("Edit").setData(row);
            });
        },
         //查看
         opShow(row) {
            this.dialogSave = true;
            this.$nextTick(() => {
                this.$refs.saveDialog.setData(row);
                this.$refs.saveDialog.open("Show");
            });
        },

        //修改状态
        async opState(row,state) {
            try {
                //撤回
                if(state==5)
                {
                    this.$confirm(`撤回将会把该单据下的物料全部进行撤回`, '提示', {type: 'warning'}).then(() => {
                        this.$API.auth.PostProcessApi.post("after-order/item-state",{ afterOrderItemId: row.afterOrderItemId,state:state}).then((result)=>{
                            if (result.status == 200) {
                                this.$message.success("撤回成功");
                                this.$refs.mytable.getData();
                            } else {
                                this.$message.error("撤回失败:" + result.msg);
                            }

                        });

                    })
                }else
                {
                        this.$API.auth.PostProcessApi.post("after-order/item-state",{ afterOrderItemId: row.afterOrderItemId,state:state}).then((result)=>{
                            if (result.status == 200) {
                                this.$message.success("操作成功");
                                this.$refs.mytable.getData();
                            } else {
                                this.$message.error("操作失败:" + result.msg);
                            }

                        });
                }

                this.auditState=false;
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        //删除
        async opDelete(row) {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "after-order/delete",
                    { afterOrderId: row.afterOrderId }
                );
                if (returnValue.status == 200) {
                    this.$message.success("操作成功");
                    this.$refs.mytable.getData();
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        //批量删除
        async opBatchDelete() {
            // eslint-disable-next-line no-debugger
            //debugger;
            this.$confirm(
                `确定删除选中的 ${this.selectionRows.length} 项吗？`,
                "提示",
                {
                    type: "warning",
                }
            )
                .then(async () => {
                    const storeIds = this.selectionRows.map(
                        (p) => p.storeId
                    );
                    try {
                        var returnValue =
                            await this.$API.auth.PostProcessApi.post(
                                "store/delete",
                                { storeIds: [...storeIds] }
                            );
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            this.$refs.mytable.getData();
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                        }
                    } catch (error) {
                        this.loading = false;
                        return false;
                    }
                })
                .catch(() => {});
        },
         //合并
        objectSpanMethod({row,column,rowIndex,columnIndex}) {
            // if (columnIndex == 1) {
            //     //合并相同的名字
            //     let nameSpan = this.getSpanNumber(this.listData, "afterOrderCode");
            //     return {
            //         rowspan: nameSpan[rowIndex],
            //         colspan: 1,
            //     };
            // }
		},
        //行点击
        rowClick(row, event, column){
            console.log("行点击",row);
            this.activeRowIndex = row.afterOrderItemId;
        },
        //选中样式
        selectedStyle({ row, rowIndex })
        {
            if (this.activeRowIndex === row.afterOrderItemId) {
                return { backgroundColor: '#87CEFF' };
            }
            return {};
        },
        //获取要合并的行数
        getSpanNumber(data, prop) {
            console.log("data",data);
            //data要处理的数组，prop要合并的属性，比如name
            //数组的长度，有时候后台可能返回个null而不是[]
            let length = Array.isArray(data) ? data.length : 0;
            if (length > 0) {
                //用于标识位置
                let position = 0;
                //用于对比的数据
                let temp = data[0][prop];

                //要返回的结果
                let result = [1];
                //假设数据是AABCC，我们的目标就是返回20120
                for (let i = 1; i < length; i++) {
                if (data[i][prop] == temp) {
                    //标识位置的数据加一
                    result[position] += 1;
                    //当前位置添0
                    result[i] = 0;
                } else {
                    //不相同时，修改标识位置，该位置设为1，修改对比值
                    position = i;
                    result[i] = 1;
                    temp = data[i][prop];
                }
                }
                //返回结果
                return result;
            } else {
                return [0];
            }
        },
        //跳转
        goTo(row){
            console.log(row.applyOrderCode)

           this.$router.push({ path: '/apply/order', query: { applyOrderCode: row.applyOrderCode} });

		},
        //表格选择后回调事件
        selectionChange(selection) {
            this.selectionRows = selection;
        },
        //本地更新数据
        handleSaveSuccess(data, mode) {
            if (mode == "Add") {
                this.$refs.mytable.refresh();
            } else if (mode == "Edit") {
                this.$refs.mytable.refresh();
            }
        },
        async opBindData() {
            this.$refs.mytable.clearSort();
            this.$refs.mytable.getData();
        },
        resetSearch() {
            this.queryList={};
        },
        async initOptions() {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "base-dictionary/options",
                    { Codes: ["AfterOrderStatus","AfterOrderType"] }
                );
                if (returnValue.status == 200) {
                    console.log("returnValue",returnValue);
					this.optionsStatus=returnValue.response.find(p=>p.code=="AfterOrderStatus").optionsDetails;
                    this.optionsAfterOrderType=returnValue.response.find(p=>p.code=="AfterOrderType").optionsDetails;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }

            try {
					await this.$API.auth.PostProcessApi.post(
						"material-type/tree",
						{ status: 1 }
					).then((result)=>{
                        if (returnValue.status == 200) {
						    this.materialTypeTree = returnValue.response;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                        }
                    });

				} catch (error) {
					this.loading = false;
					return false;
				}
        },
        //图片预览
        handlePreview(row) {
            if (!row.materialImages || row.materialImages.length == 0) {
                return;
            }
            this.previewUrl = row.materialImages[0]; // 设置当前预览的图片 URL
            this.srcList = row.materialImages; // 设置预览列表
            this.showImage = true; // 显示 el-image

        },
        closeViewer(){
            this.showImage = false; 
        },
    },
    async mounted() {

        console.log("结果：", this.getSpanNumber(this.listData, "afterOrderCode"));
        this.orgType = tool.data.get("USER_INFO").AccountType;
        var afterOrderCode=this.$route.query.afterOrderCode;
        if(afterOrderCode){
            this.queryList.afterOrderCode=afterOrderCode;
        }
        await this.initOptions();
        await this.opBindData();
    },
};
</script>
<style scoped>
	.goto{
		color: blue;
		text-decoration: underline;
		cursor:pointer;
	}
    .el-form-item {
        margin-bottom: 5px; /* 调整这个值来改变间隔 */
    }
</style>
